package com.wolfking.converter.web;

import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.wolfking.converter.transform.AbstractExtendTransform;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/sql")
public class AjaxController {


    private final Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();


    @ResponseBody
    @PostMapping(value = "/json", consumes = "application/json;charset=UTF-8")
    public Map<String, ?> jsonFormat(@RequestBody String json) {
        try {
            JsonElement element = JsonParser.parseString(json);
            if (element.isJsonNull() || element.isJsonPrimitive()) {
                throw new RuntimeException();
            }
            return ImmutableMap.of("isJson", true, "text", gson.toJson(element));
        } catch (Exception e) {
            return ImmutableMap.of("isJson", false, "text", json.trim());
        }
    }

    @ResponseBody
    @PostMapping(value = "/json4html", consumes = "application/json;charset=UTF-8")
    public Map<String, ?> jsonFormat4html(@RequestBody String json) {
        try {
            JsonElement element = JsonParser.parseString(json);
            return ImmutableMap.of("isJson", true, "text", gson.toJson(element).replace("\n", "<BR>")
                    .replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
                    .replace(" ", "&nbsp;&nbsp;"));
        } catch (Exception e) {
            return ImmutableMap.of("isJson", false, "text", json.trim());
        }
    }


    @ResponseBody
    @SuppressWarnings("all")
    @GetMapping(value = "/converterParam", consumes = "application/json;charset=UTF-8")
    public Map<String, ?> converterParam(@RequestParam String classname) {
        try {
            AbstractExtendTransform transform = (AbstractExtendTransform) Class.forName(classname).newInstance();
            return ImmutableMap.of("success", true, "exampleConfig", transform.getExampleConfig(),
                    "exampleConfigDesc", transform.getExampleConfigDesc());
        } catch (Throwable e) {
            return ImmutableMap.of("success", false);
        }
    }

}
